import React, {useState, useEffect} from 'react'
import { useNavigate, Navigate } from 'react-router-dom';
import { DatePicker, Button, Modal } from 'antd';
import http from '@utils/http'
import Icon from '@components/icon';
import Chart from './components/chart';
import PieChart from './components/pieChart';
import NoChart from '@components/empty/noChart';
import CreateTransactionModal from './components/createTransactionModal'
import dayjs from 'dayjs';
import './styles/index.less'

const Home = (props) => {
  const [chartYear, setChartYear] = useState(dayjs('2025'))
  const [assetList, setAssetList] = useState([])
  const [assetInfo, setAssetInfo] = useState({})
  const [chartData, setChartData] = useState([])
  const navigate = useNavigate();

  useEffect(() => {
    getAssetsData()
    getAssetTotalStatistics(chartYear.year())
  }, [])

  const ipcHandle = () => window.electron.ipcRenderer.send('ping')

  const getAssetTotalStatistics = (year) => {
    http.get('assetAllChartData', {
      year
    }).then(res => {
      console.log('res.data', res.data)
      setChartData(res.data)
    })
  }

  const calculateAssets = (data) => {
    if (!data) return {
      totalAsset: '-',
      totalLiability: '-',
      netAsset: '-'
    }

    let totalAsset = 0;
    let totalLiability = 0;

    data.forEach(item => {
      const amount = parseFloat(item.totalAmount);

      if (item.id === 2) {
        totalLiability += amount;
      } else {
        totalAsset += amount;
      }
    });

    const netAsset = totalAsset - totalLiability;

    return {
      totalAsset: totalAsset.toFixed(2),
      totalLiability: totalLiability.toFixed(2),
      netAsset: netAsset.toFixed(2)
    };
  }

  const getAssetsData = () => {
    http.get('assets').then(res => {
      setAssetInfo(calculateAssets(res.data))
      setAssetList(res.data)
    }).catch(err => {
    })
  }

  const onChangeDatePicker = (date) => {
    setChartYear(date)
    getAssetTotalStatistics(date.year())
  }

  const handleChartYear = (date) => {
    setChartYear(date)
    getAssetTotalStatistics(date.year())
  }

  const openCreateTransaction = () => {
    Modal.info({
      width: 400,
      modalRender: () => <CreateTransactionModal onUpdate={() => {
        getAssetsData()
        getAssetTotalStatistics(chartYear.year())
      }} {...props} />
    })
  }

  const pieChartData = assetList ? assetList.filter(item => item.totalAmount !== '0.00') : []

  return (
    <>
      <div className="home">
        <div className="home-header">
          <div className="asset-box">
            <div className="asset-box-title">
              <span>我的资产</span>
              <Button className="create-deal-btn" onClick={() => openCreateTransaction()} icon={
                <svg t="1756781951085" class="icon" viewBox="0 0 1052 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="20848" width="15" height="15"><path d="M696.100571 555.154286a35.035429 35.035429 0 1 1 0 69.997714H550.765714v140.946286a36.571429 36.571429 0 0 1-72.557714 0V625.152H327.899429a35.035429 35.035429 0 1 1 0-69.997714h150.089142V446.976H327.899429a35.035429 35.035429 0 1 1 0-69.997714h97.206857L348.891429 303.469714a34.084571 34.084571 0 0 1 0-49.517714 37.229714 37.229714 0 0 1 51.2 0L512.219429 362.057143l119.588571-115.273143a37.229714 37.229714 0 0 1 51.2 0 34.084571 34.084571 0 0 1 0 49.517714l-83.675429 80.457143h96.402286a35.035429 35.035429 0 1 1 0 69.997714H550.4v108.178286zM793.161143 1022.610286a32.841143 32.841143 0 0 1-23.552-9.947429l-97.133714-99.401143a32.914286 32.914286 0 1 1 47.104-46.006857l40.667428 41.618286V670.793143a32.914286 32.914286 0 0 1 65.828572 0v318.829714a32.914286 32.914286 0 0 1-32.914286 32.914286zM918.747429 1022.610286a32.914286 32.914286 0 0 1-32.914286-32.914286V670.866286a32.914286 32.914286 0 0 1 56.466286-22.966857l97.133714 99.401142a32.914286 32.914286 0 1 1-47.104 46.006858l-40.667429-41.618286v238.08a32.914286 32.914286 0 0 1-32.914285 32.841143z" p-id="20849" fill="#000000"></path><path d="M512 1024a512.585143 512.585143 0 0 1-512-512 512.585143 512.585143 0 0 1 512-512 512.585143 512.585143 0 0 1 512 512h-87.771429a421.595429 421.595429 0 0 0-124.342857-299.885714A421.229714 421.229714 0 0 0 512 87.771429 424.740571 424.740571 0 0 0 87.771429 512 424.667429 424.667429 0 0 0 512 936.228571V1024z" p-id="20850" fill="#000000"></path></svg>
              }>调整余额</Button>
            </div>
            <div className="asset-box-content">
              {
                assetList && assetList.map(item => (
                  <div className="asset-item" key={item.id} onClick={() => navigate(`/asset/${item.id}?name=${item.name}`)}>
                    <div className="asset-item-icon"><Icon path={item.icon} width={20} height={20} fill="#000" /></div>
                    <div className="asset-item-info">
                      <div className="asset-item-title">{item.name}</div>
                      <div className="asset-item-money amount-family">￥{item.id === 2 ? (item.totalAmount * -1).toFixed(2) : item.totalAmount}</div>
                    </div>
                  </div>
                ))
              }
            </div>
          </div>
          <div className="cross-line"></div>
          <div className="statistics-box">
            <div className="statistics-box-title">财务统计</div>
            <div className="statistics-box-content">
              <div className="statistics-item net-assets">
                <div className="statistics-item-title">净资产</div>
                <div className="statistics-item-money amount-family">￥{assetInfo.netAsset}</div>
              </div>
              <div className="statistics-item total-assets">
                <div className="statistics-item-title">总资产</div>
                <div className="statistics-item-money amount-family">￥{assetInfo.totalAsset}</div>
              </div>
              <div className="statistics-item total-liabilities">
                <div className="statistics-item-title">总负债</div>
                <div className="statistics-item-money amount-family">￥{assetInfo.totalLiability}</div>
              </div>
            </div>
          </div>
        </div>
        <div className="home-main">
          <div className="chart-box">
            <div className="chart-header">
              <ul className="chart-sign">
                <li className="net-assets-sign">净资产</li>
                <li className="total-assets-sign">总资产</li>
                <li className="total-liabilities-sign">总负债</li>
              </ul>
              <div className="year-select">
                <i className="year-prev-icon" onClick={() => handleChartYear(dayjs(chartYear).subtract(1, 'year'))}>
                  <svg fill="none" height="16" viewBox="0 0 16 16" width="16"><clipPath id="a"><path d="m0 0h16v16h-16z" transform="matrix(-1 0 0 -1 16 16)"/></clipPath><g clipPath="url(#a)" fill="#000"><path d="m8.64665 11.3533c.04577.0491.10097.0885.1623.1159.06134.0273.12755.042.19468.0432.06714.0012.13382-.0112.19608-.0363.06226-.0252.11882-.0626.16629-.1101.04748-.0475.08491-.104.11006-.1663.02515-.0622.0375-.1289.03631-.1961-.00118-.0671-.01588-.1333-.0432-.1946-.02733-.0614-.06673-.1166-.11586-.1624l-2.64666-2.64662 2.64666-2.64667c.04913-.04577.08853-.10097.11586-.16231.02732-.06133.04202-.12754.0432-.19467.00119-.06714-.01116-.13382-.03631-.19608s-.06258-.11882-.11006-.1663c-.04747-.04748-.10403-.08491-.16629-.11005-.06226-.02515-.12894-.0375-.19608-.03632-.06713.00119-.13334.01588-.19468.04321-.06133.02733-.11653.06673-.1623.11586l-3 3c-.09364.09375-.14623.22083-.14623.35333s.05259.25958.14623.35333z"/><path d="m0 8c0 4.418 3.582 8 8 8s8-3.582 8-8-3.582-8-8-8-8 3.582-8 8zm1 0c0-3.866 3.134-7 7-7s7 3.134 7 7-3.134 7-7 7-7-3.134-7-7z"/></g></svg>
                </i>
                <div className="year-select-text">
                  <DatePicker className="year-select-input" value={chartYear} defaultValue={chartYear} placeholder="" format="YYYY年" allowClear={false} inputReadOnly={true} variant="borderless" suffixIcon={null} onChange={onChangeDatePicker} picker="year" />
                </div>
                <i className={chartYear.isSame(dayjs(), 'year') ? 'year-next-icon forbid' : 'year-next-icon'} onClick={() => handleChartYear(dayjs(chartYear).add(1, 'year'))}>
                  <svg fill="none" height="16" viewBox="0 0 16 16" width="16"><clipPath id="a"><path d="m0 0h16v16h-16z" transform="matrix(-1 0 0 -1 16 16)"/></clipPath><g clipPath="url(#a)" fill="#000"><path d="m8.64665 11.3533c.04577.0491.10097.0885.1623.1159.06134.0273.12755.042.19468.0432.06714.0012.13382-.0112.19608-.0363.06226-.0252.11882-.0626.16629-.1101.04748-.0475.08491-.104.11006-.1663.02515-.0622.0375-.1289.03631-.1961-.00118-.0671-.01588-.1333-.0432-.1946-.02733-.0614-.06673-.1166-.11586-.1624l-2.64666-2.64662 2.64666-2.64667c.04913-.04577.08853-.10097.11586-.16231.02732-.06133.04202-.12754.0432-.19467.00119-.06714-.01116-.13382-.03631-.19608s-.06258-.11882-.11006-.1663c-.04747-.04748-.10403-.08491-.16629-.11005-.06226-.02515-.12894-.0375-.19608-.03632-.06713.00119-.13334.01588-.19468.04321-.06133.02733-.11653.06673-.1623.11586l-3 3c-.09364.09375-.14623.22083-.14623.35333s.05259.25958.14623.35333z"/><path d="m0 8c0 4.418 3.582 8 8 8s8-3.582 8-8-3.582-8-8-8-8 3.582-8 8zm1 0c0-3.866 3.134-7 7-7s7 3.134 7 7-3.134 7-7 7-7-3.134-7-7z"/></g></svg>
                </i>
              </div>
            </div>
            <Chart data={chartData} />
          </div>
          <div className="pie-chart-box">
            {/* <div className="log-title">资产占比</div> */}
            <div className="pie-chart-main">
              {
                pieChartData.length > 0 ? <PieChart data={assetList} /> : <NoChart />
              }
            </div>
          </div>
        </div>
        {/* <h1>Home Page</h1>
        <button onClick={() => navigate('/login')}>Go to Login</button>
        <div className="actions">
          <div className="action">
            <a target="_blank" rel="noreferrer" onClick={() => getAssetsData()}>
              Documentation
            </a>
          </div>
          <div className="action">
            <a target="_blank" rel="noreferrer" onClick={ipcHandle}>
              Send IPC
            </a>
          </div>
        </div> */}
      </div>
    </>
  )
}

export default Home;